/*
  let url = 'http://demo.com/api'
  例:
  fetchHttp(url)
    .then( res => {
      console.log(res)
    })
    .catch( e => {
      console.log(e)
    })
  fetchHttp(url, {
    method: 'POST',
  })
*/
import {
  param
} from './help'

export const fetchHttp = (url, setting = {}) => {
  // 设置参数的初始值
  const opts = {
    method: (setting.method || 'GET').toUpperCase(), // 请求方式
    headers: setting.headers || {}, // 请求头设置
    credentials: setting.credentials || 'include', // 设置cookie是否一起发送
    body: setting.body || {},
    mode: setting.mode || 'cors', // 可以设置 cors, no-cors, same-origin
    redirect: setting.redirect || 'follow', // follow, error, manual
    cache: setting.cache || 'default' // 设置 cache 模式 (default, reload, no-cache)
  }
  const dataType = setting.dataType || 'json' // 解析方式
  const data = setting.data || '' // 参数

  if (opts.method === 'GET') {
    url += (data ? `?${param(data)}` : '')
  } else {
    setting.body = data || {}
  }
  return new Promise((resolve, reject) => {
    fetch(url, opts).then(async (res) => {
      let resData = null
      switch (dataType) {
        case 'text':
          resData = await res.text()
          break
        case 'blob':
          resData = await res.blob()
          break
        default:
          resData = await res.json()
          break
      }
      resolve(resData)
    }).catch((e) => {
      reject(e)
    })
  })
}
